package hlhj.fhp.supreme.customview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

import fhp.hlhj.giantfold.utils.ToastUtils;
import hlhj.fhp.supreme.utils.MyUtils;

/**
 * Created by Never Fear   on 2018\7\23 0023.
 * Never More....
 */

@SuppressLint("AppCompatCustomView")
public class MarqueeView extends TextView implements Runnable {
    private int currentScrollX;// 当前滚动的位置
    private boolean isStop = false;
    private int textWidth;
    private boolean isMeasure = false;

    public MarqueeView(Context context) {
        super(context);
        init();
    }

    public MarqueeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MarqueeView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init(){
        setVisibility(INVISIBLE);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (!isMeasure) {// 文字宽度只需获取一次就可以了
            getTextWidth();
            isMeasure = true;
        }
    }

    /**
     * 获取文字宽度
     */
    private void getTextWidth() {
        Paint paint = this.getPaint();
        String str = this.getText().toString();
        textWidth = (int) paint.measureText(str);
    }

    @Override
    public void run() {
        scrollTo(currentScrollX - getWidth(), 0);
        setVisibility(View.VISIBLE);
        currentScrollX += 1;// 滚动速度
        if (isStop) {
            return;
        }
        if (currentScrollX > (this.getWidth() + textWidth)) {
            currentScrollX = 0;
        }
        postDelayed(this, 5);
    }

    // 开始滚动
    public void startScroll() {
        isStop = false;
        this.removeCallbacks(this);
        post(this);
    }

    @Override
    public boolean isFocused() {
        return true;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if (false){
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
        }
        return;
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        if (false){
            super.onWindowFocusChanged(hasWindowFocus);
        }
    }

    // 停止滚动
    public void stopScroll() {
        isStop = true;
    }

    // 从头开始滚动
    public void startFor0() {
        currentScrollX = 0;
        startScroll();
    }
}